<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/lion_fa.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/lion_fa.ico?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="后端,">










<meta name="description" content="前段时间自己瞎折腾了一下Node，作为一个专业的前端肯定要了解多点后端知识啦，瞎折腾了一番Node和Mongo，发现了一好用的玩意叫mongoose。简单理解就是一个更加便捷操作MongoDB对象的工具。  NodeJS和Mongo的教程不写了，网上一堆堆的… 一、准备工作1. 启动mongo数据库关于下载安装启动数据库我这里就不做过多解释，谷歌下会有很多教程，启动成功后的命令窗如下所示：  i">
<meta name="keywords" content="后端">
<meta property="og:type" content="article">
<meta property="og:title" content="后端之路开启，入门mongoose">
<meta property="og:url" content="http://loren.gitee.io/blog/2018/02/01/技术/入门Mongoose/index.html">
<meta property="og:site_name" content="Geron Zhang的碎碎念">
<meta property="og:description" content="前段时间自己瞎折腾了一下Node，作为一个专业的前端肯定要了解多点后端知识啦，瞎折腾了一番Node和Mongo，发现了一好用的玩意叫mongoose。简单理解就是一个更加便捷操作MongoDB对象的工具。  NodeJS和Mongo的教程不写了，网上一堆堆的… 一、准备工作1. 启动mongo数据库关于下载安装启动数据库我这里就不做过多解释，谷歌下会有很多教程，启动成功后的命令窗如下所示：  i">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-43d01c8bf5dd697f.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-ce09ba20fb2cd473.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-81772950ee3010b4.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-73a12062f21609cc.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-f57c1eeb8f8d7c9e.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-e27735c950cf71b0.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-6d9862a7e070fa1a.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-be4cc9ad259bc57e.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-dafbd8b8001b5b22.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-313a64de374b3a20.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-7e5d0a6243ba97a0.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-6751c4cdbbb672bd.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-41c8ddb16371bbdf.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-0b490ab4037c02a7.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-7070ddbc47143391.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/5454392-b6363f8960d4370a.png">
<meta property="og:updated_time" content="2019-05-07T17:06:46.675Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="后端之路开启，入门mongoose">
<meta name="twitter:description" content="前段时间自己瞎折腾了一下Node，作为一个专业的前端肯定要了解多点后端知识啦，瞎折腾了一番Node和Mongo，发现了一好用的玩意叫mongoose。简单理解就是一个更加便捷操作MongoDB对象的工具。  NodeJS和Mongo的教程不写了，网上一堆堆的… 一、准备工作1. 启动mongo数据库关于下载安装启动数据库我这里就不做过多解释，谷歌下会有很多教程，启动成功后的命令窗如下所示：  i">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/5454392-43d01c8bf5dd697f.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://loren.gitee.io/blog/2018/02/01/技术/入门Mongoose/">





  <title>后端之路开启，入门mongoose | Geron Zhang的碎碎念</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c17a01cf17d1b4db888987342f5b01cb";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Geron Zhang的碎碎念</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Slowly&&Forward</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://loren.gitee.io/blog/blog/2018/02/01/技术/入门Mongoose/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Geron Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Geron Zhang的碎碎念">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">后端之路开启，入门mongoose</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-02-01T15:35:35+08:00">
                2018-02-01
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/技术/" itemprop="url" rel="index">
                    <span itemprop="name">技术</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2018/02/01/技术/入门Mongoose/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/blog/2018/02/01/技术/入门Mongoose/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/blog/2018/02/01/技术/入门Mongoose/" class="leancloud_visitors" data-flag-title="后端之路开启，入门mongoose">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>前段时间自己瞎折腾了一下Node，作为一个专业的前端肯定要了解多点后端知识啦，瞎折腾了一番Node和Mongo，发现了一好用的玩意叫mongoose。简单理解就是一个更加便捷操作MongoDB对象的工具。</p>
</blockquote>
<p>NodeJS和Mongo的教程不写了，网上一堆堆的…</p>
<h2 id="一、准备工作"><a href="#一、准备工作" class="headerlink" title="一、准备工作"></a>一、准备工作</h2><h3 id="1-启动mongo数据库"><a href="#1-启动mongo数据库" class="headerlink" title="1. 启动mongo数据库"></a>1. 启动mongo数据库</h3><p>关于下载安装启动数据库我这里就不做过多解释，谷歌下会有很多教程，启动成功后的命令窗如下所示：</p>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-43d01c8bf5dd697f.png" alt></p>
<p>image</p>
<h3 id="2-启用可视化Mongo工具"><a href="#2-启用可视化Mongo工具" class="headerlink" title="2. 启用可视化Mongo工具"></a>2. 启用可视化Mongo工具</h3><p>这里我们用的是Robo 3T，为什么要用可视化工具呢，因为小白对于命令行还是很陌生的，在命令行中查看数据库的内容有些不直观，这个可视化工具的安装包谷歌一下就阔以找到啦～</p>
<ol>
<li><p>启动可视化工具</p>
</li>
<li><p>连接数据库（前提是已经启动了mongo数据库）</p>
</li>
</ol>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-ce09ba20fb2cd473.png" alt></p>
<p>image</p>
<ol>
<li>新建数据库mongoosetest</li>
</ol>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-81772950ee3010b4.png" alt></p>
<p>image</p>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-73a12062f21609cc.png" alt></p>
<p>image</p>
<ol>
<li>创建成功</li>
</ol>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-f57c1eeb8f8d7c9e.png" alt></p>
<p>image</p>
<p>数据库准备工作完成后，我们进入代码环节啦～</p>
<h2 id="二、利用mongoose进行简单的数据库操作"><a href="#二、利用mongoose进行简单的数据库操作" class="headerlink" title="二、利用mongoose进行简单的数据库操作"></a>二、利用mongoose进行简单的数据库操作</h2><h3 id="1-新建项目"><a href="#1-新建项目" class="headerlink" title="1. 新建项目"></a>1. 新建项目</h3><ol>
<li><p>新建空文件夹，命名为mongooseTest</p>
</li>
<li><p>启动终端，进入该文件夹</p>
</li>
<li><p>在命令行中输入npm init 初始化项目<pre>npm&nbsp;init</pre></p>
</li>
</ol>
<p>这里有个小问题就是项目不能以驼峰命名，所以npm init后会让你输入一个别名，我们就叫mongoosetest好了，然后一直Enter，项目创建成功。</p>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-e27735c950cf71b0.png" alt></p>
<p>image</p>
<ol>
<li><p>下载依赖包 mongoose<pre>npm&nbsp;i&nbsp;mongoose&nbsp;-s</pre></p>
</li>
<li><p>完成项目创建，项目结构：</p>
</li>
</ol>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-6d9862a7e070fa1a.png" alt></p>
<p>image</p>
<h3 id="2-连接数据库"><a href="#2-连接数据库" class="headerlink" title="2. 连接数据库"></a>2. 连接数据库</h3><p>在根目录下创建db.js，输入以下代码，监听connection的几个事件，如果以上操作都没错的话，那么就会监听第一个事件“connect”事件，表示连接数据库成功，在最后，我们导出mongoose对象，以供其他模块使用。</p>
<pre>/**
&nbsp;*&nbsp;Created&nbsp;by&nbsp;vince&nbsp;on&nbsp;2017/7/10.
&nbsp;*&nbsp;db.js
&nbsp;*/var&nbsp;mongoose&nbsp;=&nbsp;require('mongoose');//设置mongo存储路径var&nbsp;DB_URL&nbsp;=&nbsp;'mongodb://localhost:27017/mongoosetest';//连接数据库mongoose.connect(DB_URL);//连接成功后输出语句mongoose.connection.on('connected',function&nbsp;()&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;console.log('Mongoose&nbsp;connect&nbsp;'&nbsp;+&nbsp;DB_URL&nbsp;+&nbsp;"&nbsp;success");
});//连接异常现实错误原因mongoose.connection.on('error',function&nbsp;(err)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;console.log('Mongoose&nbsp;connect&nbsp;Error:'&nbsp;+&nbsp;err);
});//连接断开后输出语句mongoose.connection.on('disconnected',function&nbsp;()&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;console.log('Mongoose&nbsp;connect&nbsp;disconnected');
});//导出mongoose对象module.exports&nbsp;=&nbsp;mongoose;</pre>

<p>运行db.js，如下图所示：</p>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-be4cc9ad259bc57e.png" alt></p>
<p>image</p>
<p>第一步连接数据库成功啦～</p>
<h3 id="3-新建Schema与发布Model"><a href="#3-新建Schema与发布Model" class="headerlink" title="3. 新建Schema与发布Model"></a>3. 新建Schema与发布Model</h3><p>那么什么是Schema呢？schema是mongoose里会用到的一种数据模式，可以理解为我们传统数据库中的表（table）结构的定义，简单地说，就是一个数据模板，每个schema会映射到mongodb中的一个collection，它不具备操作数据库的能力。</p>
<p>那什么又是Model呢？Model是由Schema发布生成的模型，具有抽象属性和行为的数据库操作对，Model可以直接操作Mongo数据库中的数据。</p>
<p>解释完了代码用说话，新建user.js，输入以下代码，创建一个user的schema，并且利用Schema发布一个Model，导出Model：</p>
<pre>/**
&nbsp;*&nbsp;Created&nbsp;by&nbsp;vince&nbsp;on&nbsp;2017/7/10.&nbsp;&nbsp;
&nbsp;*&nbsp;user.js
&nbsp;*///引入之前我们创建的mongose对象var&nbsp;mongoose&nbsp;=&nbsp;require('./db.js');//创建一个schema对象var&nbsp;Schema&nbsp;=&nbsp;mongoose.Schema;//创建一个schema实例var&nbsp;UserSchema&nbsp;=&nbsp;new&nbsp;Schema({&nbsp;&nbsp;&nbsp;&nbsp;username:&nbsp;{type:&nbsp;String},&nbsp;&nbsp;&nbsp;&nbsp;userpwd:&nbsp;{type:&nbsp;String},&nbsp;&nbsp;&nbsp;&nbsp;userage:&nbsp;{type:&nbsp;Number},&nbsp;&nbsp;&nbsp;&nbsp;logindate:&nbsp;{type:&nbsp;Date}
});//利用UserSchema实例,发布一个User的model并且导出module.exports&nbsp;=&nbsp;mongoose.model("User",UserSchema);</pre>

<h3 id="4-Model创造Entity实体，对数据库操作"><a href="#4-Model创造Entity实体，对数据库操作" class="headerlink" title="4. Model创造Entity实体，对数据库操作"></a>4. Model创造Entity实体，对数据库操作</h3><p>那Entity又是什么呢？Entity是由Model创建的实体，他的操作也会影响数据库。</p>
<ul>
<li>新建insert.js,输入以下代码：<pre>/*<em><br>&nbsp;</em>&nbsp;Created&nbsp;by&nbsp;vince&nbsp;on&nbsp;2017/7/10.<br>&nbsp;<em>&nbsp;insert.js<br>&nbsp;</em>///引如User的Modelvar&nbsp;User&nbsp;=&nbsp;require(‘./user’);//创建一个插入数据到数据库中的函数function&nbsp;insert()&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;//用Model创建一个Entity实体，就是一个User的数据<br>&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;user_1&nbsp;=&nbsp;new&nbsp;User({&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;username:&nbsp;’Vince&nbsp;Hua’,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;userpwd:&nbsp;’123456’,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;userage:&nbsp;20,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;logindate:&nbsp;new&nbsp;Date()<br>&nbsp;&nbsp;&nbsp;&nbsp;});&nbsp;&nbsp;&nbsp;&nbsp;//调用user_1的save方法，插入user_1的数据到数据库中<br>&nbsp;&nbsp;&nbsp;&nbsp;user_1.save(function&nbsp;(err,&nbsp;res)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(err){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log(“Error:&nbsp;”&nbsp;+&nbsp;err);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}else{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log(“Success&nbsp;Res:&nbsp;”&nbsp;+&nbsp;res)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;&nbsp;&nbsp;});<br>}//执行插入操作insert();</pre></li>
</ul>
<p>以上代码中的user_1就是Model创建的Entity实体，它具有很多操作，svae()只是其中一个。</p>
<ul>
<li>运行insert.js，命令行输入框得到一下结果：</li>
</ul>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-dafbd8b8001b5b22.png" alt></p>
<p>image</p>
<ul>
<li>我们再查看数据库中：</li>
</ul>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-313a64de374b3a20.png" alt></p>
<p>image</p>
<ul>
<li>Amazing，我们成功插入一个数据啦～</li>
</ul>
<h3 id="5-总结Schema、Model、Entity的关系"><a href="#5-总结Schema、Model、Entity的关系" class="headerlink" title="5. 总结Schema、Model、Entity的关系"></a>5. 总结Schema、Model、Entity的关系</h3><ul>
<li><p>Schema &nbsp;： &nbsp;一种以文件形式存储的数据库模型骨架，不具备数据库的操作能力</p>
</li>
<li><p>Model &nbsp; ： &nbsp;由Schema发布生成的模型，具有抽象属性和行为的数据库操作对</p>
</li>
<li><p>Entity &nbsp;： &nbsp;由Model创建的实体，他的操作也会影响数据库</p>
</li>
<li><p>Schema、Model、Entity的关系是：Schema生成Model，Model创造Entity，Model和Entity都可对数据库操作造成影响，但Model比Entity更具操作性。</p>
</li>
</ul>
<h2 id="三、mongoose的其他一些-“骚操作”"><a href="#三、mongoose的其他一些-“骚操作”" class="headerlink" title="三、mongoose的其他一些 “骚操作”"></a>三、mongoose的其他一些 “骚操作”</h2><ul>
<li><h4 id="更新数据库"><a href="#更新数据库" class="headerlink" title="更新数据库"></a>更新数据库</h4></li>
</ul>
<p>这里我们是直接用Model来操作数据库，新建update.js</p>
<pre>/**
&nbsp;*&nbsp;Created&nbsp;by&nbsp;vince&nbsp;on&nbsp;2017/7/10.
&nbsp;*&nbsp;update.js
&nbsp;*///引入User的Modelvar&nbsp;User&nbsp;=&nbsp;require("./user.js");function&nbsp;update(){&nbsp;&nbsp;&nbsp;&nbsp;//wherestr是我们要进行操作的数据
&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;wherestr&nbsp;=&nbsp;{'username'&nbsp;:&nbsp;'Vince&nbsp;Hua'};&nbsp;&nbsp;&nbsp;&nbsp;//update是我们更新的数据
&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;updatestr&nbsp;=&nbsp;{'userpwd':&nbsp;'hhhhhh'};

&nbsp;&nbsp;&nbsp;&nbsp;User.update(wherestr,&nbsp;updatestr,&nbsp;function(err,&nbsp;res){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(err)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log("Error:"&nbsp;+&nbsp;err);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;else&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log("Update&nbsp;Res:&nbsp;"&nbsp;+&nbsp;res);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;})
}

update();</pre>

<ul>
<li>运行updata.js，操作成功，命令行输出：</li>
</ul>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-7e5d0a6243ba97a0.png" alt></p>
<p>image</p>
<ul>
<li>更新成功，查看数据库：</li>
</ul>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-6751c4cdbbb672bd.png" alt></p>
<p>image</p>
<ul>
<li><h4 id="删除数据"><a href="#删除数据" class="headerlink" title="删除数据"></a>删除数据</h4></li>
</ul>
<p>同样我们直接用Model操作数据库，新建remove.js，输入以下代码：</p>
<pre>/**
&nbsp;*&nbsp;Created&nbsp;by&nbsp;vince&nbsp;on&nbsp;2017/7/10.
&nbsp;*&nbsp;remove.js
&nbsp;*/var&nbsp;User&nbsp;=&nbsp;require("./user");function&nbsp;del()&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;//需要删除的数据
&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;wherestr&nbsp;=&nbsp;{'username'&nbsp;:&nbsp;'Vince&nbsp;Hua'};

&nbsp;&nbsp;&nbsp;&nbsp;User.remove(wherestr,function&nbsp;(err,&nbsp;res)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(err){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log("Error:&nbsp;"&nbsp;+&nbsp;err)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}else{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log("Success&nbsp;Remove:&nbsp;"&nbsp;+&nbsp;res);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;})
}

del();</pre>

<ul>
<li>执行代码，得到一下结果：</li>
</ul>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-41c8ddb16371bbdf.png" alt></p>
<p>image</p>
<ul>
<li>查看数据库，显示数据已经被删除</li>
</ul>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-0b490ab4037c02a7.png" alt></p>
<p>image</p>
<ul>
<li><h4 id="查找数据"><a href="#查找数据" class="headerlink" title="查找数据"></a>查找数据</h4></li>
<li><p>查找数据之前，我们插入一下几个数据</p>
</li>
</ul>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-7070ddbc47143391.png" alt></p>
<p>image</p>
<p>依旧是使用Model操作数据库，新建find.js，输入以下代码：</p>
<pre>/**
&nbsp;*&nbsp;Created&nbsp;by&nbsp;vince&nbsp;on&nbsp;2017/7/10.
&nbsp;*&nbsp;find.js
&nbsp;*/var&nbsp;User&nbsp;=&nbsp;require('./user');function&nbsp;findByConditions()&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;wherestr&nbsp;=&nbsp;{'username'&nbsp;:&nbsp;'Mike&nbsp;Guo'};
&nbsp;&nbsp;&nbsp;&nbsp;User.find(wherestr,function&nbsp;(err,&nbsp;res)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(err){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log("Error:&nbsp;"&nbsp;+&nbsp;err);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}else{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log("Find&nbsp;Res:&nbsp;"&nbsp;+&nbsp;res);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;});
}
findByConditions();</pre>

<ul>
<li>执行代码，得到查询结果：</li>
</ul>
<p><img src="//upload-images.jianshu.io/upload_images/5454392-b6363f8960d4370a.png" alt></p>
<p>image</p>
<h2 id="四、总结"><a href="#四、总结" class="headerlink" title="四、总结"></a>四、总结</h2><p>这里介绍的知识简单的mongoose的增删改查操作，只是方便我们第一次接触Mongo入门的小练习的Demo而已，mongoose还有其他强大的操作这里没有一一介绍，希望小伙伴们可以查看<a href="https://link.jianshu.com?t=https://mongoose.shujuwajue.com/" target="_blank" rel="noopener">中文文档</a>了解更多，如果你看了这篇文章觉得自己已经入门啦，那么恭喜你～</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/后端/" rel="tag"># 后端</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/01/25/产品/微信的优与劣/" rel="next" title="微信的优与劣">
                <i class="fa fa-chevron-left"></i> 微信的优与劣
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/04/17/生活/科比和他退役两年后的NBA/" rel="prev" title="科比和他退役两年后的NBA">
                科比和他退役两年后的NBA <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/blog/images/avatar.png" alt="Geron Zhang">
            
              <p class="site-author-name" itemprop="name">Geron Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/ZhangLorne" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:long642977312@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="/images/ecode.jpg" target="_blank" title="Wechat">
                      
                        <i class="fa fa-fw fa-wechat"></i>Wechat</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://instagram.com/Funny291" target="_blank" title="Instagram">
                      
                        <i class="fa fa-fw fa-instagram"></i>Instagram</a>
                  </span>
                
            </div>
          
          
          <iframe allowtransparency src="/blog/images/mp3.html?rel=0&amp;autoplay=1" frameborder="0" scrolling="no" width="100%">
          </iframe>

          
          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、准备工作"><span class="nav-number">1.</span> <span class="nav-text">一、准备工作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-启动mongo数据库"><span class="nav-number">1.1.</span> <span class="nav-text">1. 启动mongo数据库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-启用可视化Mongo工具"><span class="nav-number">1.2.</span> <span class="nav-text">2. 启用可视化Mongo工具</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、利用mongoose进行简单的数据库操作"><span class="nav-number">2.</span> <span class="nav-text">二、利用mongoose进行简单的数据库操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-新建项目"><span class="nav-number">2.1.</span> <span class="nav-text">1. 新建项目</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-连接数据库"><span class="nav-number">2.2.</span> <span class="nav-text">2. 连接数据库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-新建Schema与发布Model"><span class="nav-number">2.3.</span> <span class="nav-text">3. 新建Schema与发布Model</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-Model创造Entity实体，对数据库操作"><span class="nav-number">2.4.</span> <span class="nav-text">4. Model创造Entity实体，对数据库操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-总结Schema、Model、Entity的关系"><span class="nav-number">2.5.</span> <span class="nav-text">5. 总结Schema、Model、Entity的关系</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、mongoose的其他一些-“骚操作”"><span class="nav-number">3.</span> <span class="nav-text">三、mongoose的其他一些 “骚操作”</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#更新数据库"><span class="nav-number">3.0.1.</span> <span class="nav-text">更新数据库</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#删除数据"><span class="nav-number">3.0.2.</span> <span class="nav-text">删除数据</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#查找数据"><span class="nav-number">3.0.3.</span> <span class="nav-text">查找数据</span></a></li></ol></li></ol><li class="nav-item nav-level-2"><a class="nav-link" href="#四、总结"><span class="nav-number">4.</span> <span class="nav-text">四、总结</span></a></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2016 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Geron Zhang</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'c4Wwl9tIGuNGAWpUVALEhMLL-gzGzoHsz',
        appKey: '73Ylo6XQCclsDBYq5aGsT70K',
        placeholder: '（建议在上方留下昵称和邮箱等信息，以便收到回复通知）',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("c4Wwl9tIGuNGAWpUVALEhMLL-gzGzoHsz", "73Ylo6XQCclsDBYq5aGsT70K");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
